package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.xml.ws.spi.http.HttpContext;
import javax.xml.ws.spi.http.HttpHandler;

import java.time.LocalDateTime;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    /**
     * 手动创建线程池
     */
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result selectShopById(Long id) {
        //缓存穿透
        //Shop shop = queryWithPassThrough(id);
        //上面方法调用工具类
        //cacheClient.get(CACHE_SHOP_KEY,id,Shop.class,this::getById,CACHE_SHOP_TTL,TimeUnit.MINUTES);
        //互斥锁解决缓存击穿
        //Shop shop = queryWithMutex(id);

        //逻辑解决缓存击穿
        //Shop shop = queryWithLogicalExpire(id);
        //上面方法调用工具类
        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        if (shop == null) {
            return Result.fail("店铺不存在！");
        }

        return Result.ok(shop);
    }

    /**
     * 逻辑解决缓存击穿
     *     1.查询redis，如果不存在就直接返回空
     *     2.如果存在，先转换成RedisData，为了获取缓存的时间字段
     *     3.获取到了缓存时间字段后，根据当前时间进行比较，如果过期了，则重建缓存，开启线程去重建缓存
     * @param id 商品id
     * @return 商品信息
     */
    public Shop queryWithLogicalExpire(Long id) {
        String s = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2.不存在,直接返回空
        if(StrUtil.isBlank(s)){
            return null;
        }
        //转换成RedisData对象
        RedisData bean = JSONUtil.toBean(s, RedisData.class);
        //获取到RedisData中的data属性，转换成需要的实体
        Shop shop = JSONUtil.toBean((JSONObject) bean.getData(),Shop.class);
        //获取设置的缓存时间
        LocalDateTime expireTime = bean.getExpireTime();
        //判断缓存时间是否在当前时间之前
        if(expireTime.isAfter(LocalDateTime.now())){
            //未过期，返回商品信息
            return shop;
        }

        //过期，重建缓存，获取互斥锁
        if(tryLock(LOCK_SHOP_KEY+id)){
            //如果存在表示获取到了锁，redis第一次添加这个key值，则新开线程去执行redis缓存操作,需保证释放锁
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    shop2Redis(id,LOCK_SHOP_TTL);
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unlock(LOCK_SHOP_KEY+id);
                }
            });
        }

        return shop;
    }


    public Shop queryWithMutex(Long id) {
        //1.根据id去redis中查询，如果存在，直接返回redis中的值
        String s = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2.不存在，则查询数据库，数据库中存在，先存入redis，后返回
        if(StrUtil.isNotBlank(s)){
            return JSONUtil.toBean(s, Shop.class);
        }

        if (null != s)return null;

        Shop shop = null;

        try {
            //实现缓存重建，获取互斥锁
            boolean isLock = tryLock(LOCK_SHOP_KEY + id);
            //判断是否成功
            if(!isLock){
                //失败，休眠并重试
                try {
                    Thread.sleep(50);
                    return queryWithMutex(id);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            shop = getById(id);
            //3.不存在，返回错误代码404
            if(null == shop){
                //缓存穿透问题，返回空也存入redis，有效时间设置少一点时间
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "",CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //存在，写入redis
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            //释放互斥锁
            unlock(LOCK_SHOP_KEY + id);
        }

        return shop;
    }

    public Shop queryWithPassThrough(Long id) {
        //1.根据id去redis中查询，如果存在，直接返回redis中的值
        String s = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2.不存在，则查询数据库，数据库中存在，先存入redis，后返回
        if(StrUtil.isNotBlank(s)){
            return JSONUtil.toBean(s, Shop.class);
        }

        if (null != s)return null;

        Shop data = getById(id);
        //3.不存在，返回错误代码404
        if(null == data){
            //缓存穿透问题，返回空也存入redis，有效时间设置少一点时间
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(data),CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return data;
    }

    /**
     * 添加锁
     * @param key redis的key
     * @return 判断是否存在
     */
    private boolean tryLock(String key){
        //setIfAbsent方法，如果key存在则返回，不存在则返回false
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent( key, key, LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(flag);
    }

    /**
     * 删除锁
     * @param key redis的key
     */
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    /**
     * 手动添加热点数据，逻辑设置redis有效时间
     * @param id 商品id
     */
    public void shop2Redis(Long id,Long expireTime) throws InterruptedException {
        Shop shop = getById(id);
        //模拟
        Thread.sleep(200);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        if(null == shop || StringUtils.isEmpty(shop.getId())){
            return Result.fail("商品id不存在");
        }
        updateById(shop);
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }
}
